// Handle uploader
App.directive('edUploader', ['$parse', 'FileUploader', 'Page', function ($parse, FileUploader, Page) {
    return {

        restrict: 'A',
        scope: {
            model : '=ngModel',
            dir: '@edUploadDir'
        },
        require: 'ngModel',

        template: function (elem, attrs) {
            var option = AppUtil.jsonfy(attrs.options);
            // 兼容老的方式
            option.multiple = option.multiple || (attrs.edMultiple == 'true');
            return '<div class="attachments margin-bottom-10" ng-if="' + option.multiple + '">'
                + '<p ng-repeat="file in model"><a href="{{file.url}}">{{file.name}}</a>'
                + '  <span class="size">({{ file.size/1024/1024|number:2 }} MB)</span>'
                + '    <a title="删除" ng-click="delete(file)"><i class="fa fa-trash-o"></i></a>'
                + '    <span class="author">{{file.author}}, {{file.time}}</span>'
                + '  </p>'
                + '</div>'
                //+ '  <input type="file" class="margin-top-10" nv-file-select="" uploader="uploader" multiple/>'
                + '<span class="btn green fileinput-button">'
                + '  <i class="fa fa-plus"></i><span>' + (option.text || '选择文件') + '</span>'
                + '  <input type="file" accept="' + (option.accept || '*') + '" nv-file-select="" uploader="uploader" ' + (option.multiple ? ' multiple' : '') + '>'
                + '</span>';
        },

        controller: ['$scope', '$element', '$rootScope', function($scope, $element, $rootScope){

            $scope.author = $rootScope.user;

            var uploader = $scope.uploader = new FileUploader({
                url: 'file/uploadEx.do'
            });

            // FILTERS
            uploader.filters.push({
                name: 'customFilter',
                fn: function (item /*{File|FileLikeObject}*/, options) {
                    return this.queue.length < 10;
                }
            });
        }],

        link: function (scope, elem, attrs, ngModelController) {
            var option = AppUtil.jsonfy(attrs.options);
            // 兼容老的方式
            option.multiple = option.multiple || (attrs.edMultiple == 'true');
            // 单个文件上传或多文件上传
            scope.multiple = option.multiple;
            var uploadDir = scope.dir || '';
            var acceptType = option.accept || '*';

            // 上传前
            scope.uploader.onBeforeUploadItem = function (item) {
                var file = item.file;
                item.formData = [{name: file.name, size: file.size, type: file.type, author: scope.author, uploadDir: uploadDir}];
            };

            // 添加文件之后就开始上传
            scope.uploader.onAfterAddingFile = function(fileItem) {
                fileItem.upload();
            };

            scope.uploader.onWhenAddingFileFailed = function(item, filter, options) {
                if (filter.name == 'fileTypeFilter') {
                    Page.notice('上传文件类型不正确！');
                } else if (filter.name == 'maxSizeFilter') {
                    Page.notice('文件大小超过限制！');
                }
            };

            if (angular.isNumber(option.maxSize)) {
                scope.uploader.filters.push({
                    name: 'maxSizeFilter',
                    fn: function (item, options) {
                        return item.size <= option.maxSize * 1000;
                    }
                });
            }

            scope.uploader.filters.push({
                name: 'fileTypeFilter',
                fn: function (item, options) {
                    var mime = item.type;
                    if ("application/msword" == mime) {
                    } else if ("application/vnd.openxmlformats-officedocument.wordprocessingml.document" == mime) {
                        mime = "application/msword";
                    } else if ("application/vnd.ms-excel" == mime) {
                        mime = "application/vnd.ms-excel";
                    } else if ("application/vnd.ms-excel application/x-excel" == mime) {
                        mime = "application/vnd.ms-excel";
                    } else if ("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" == mime) {
                        mime = "application/vnd.ms-excel";
                    } else if ("application/vnd.ms-powerpoint" == mime) {
                    } else if ("application/vnd.openxmlformats-officedocument.presentationml.presentation" == mime) {
                        mime = "application/vnd.ms-powerpoint";
                    } else if ("application/vnd.ms-powerpoint" == mime) {
                        //mime = "pps";
                    } else if ("application/vnd.openxmlformats-officedocument.presentationml.slideshow" == mime) {
                        mime = "application/vnd.ms-powerpoint";
                    } else if ("application/pdf" == mime) {
                        //mime = "pdf";
                    } else if ("application/x-shockwave-flash" == mime) {
                        //mime = "swf";
                    } else if ("application/x-msdownload" == mime) {
                        //mime = "exe";
                    } else if ("application/octet-stream" == mime) {
                        var reg = new RegExp(".rar$");
                        if (item.name != null && reg.test(item.name)) {
                            mime = "rar";
                        } else {
                            mime = "exe";
                        }
                    } else if ("application/x-tar" == mime || "application/x-compressed" == mime
                        || "application/x-zip-compressed" == mime || "application/x-compress" == mime) {
                        mime = "rar";
                    } else if ("audio/wav" == mime) {
                        //mime = "wav";
                    } else if ("audio/x-ms-wma" == mime) {
                        //mime = "wma";
                    } else if ("video/x-ms-wmv" == mime) {
                        //mime = "wmv";
                    } else if ("audio/mpeg" == mime) {
                        //mime = "mp3";
                    } else if ("application/vnd.rn-realmedia" == mime) {
                        //mime = "rm";
                    } else if ("audio/mid" == mime) {
                        //mime = "mid";
                    } else if ("image/bmp" == mime) {
                        //mime = "bmp";
                    } else if ("image/gif" == mime) {
                        //mime = "gif";
                    } else if ("image/png" == mime) {
                        //mime = "png";
                    } else if ("image/tiff" == mime) {
                        //mime = "tif";
                    } else if ("image/jpeg" == mime) {
                        //mime = "jpg";
                    } else if ("text/plain" == mime) {
                        //mime = "txt";
                    } else if ("text/xml" == mime) {
                        //mime = "xml";
                    } else if ("text/html" == mime) {
                        //mime = "html";
                    } else if ("text/css" == mime) {
                        //mime = "css";
                    } else if ("text/javascript" == mime) {
                        //mime = "js";
                    } else if ("message/rfc822" == mime) {
                        //mime = "mht";
                    } else {
                        var index = item.name.lastIndexOf('.');
                        if (index > 0) {
                            mime = item.name.substring(index + 1);
                        } else {
                            mime = "unknown";
                        }
                    }
                    var accept = acceptType.trim() == '*';
                    if (!accept) {
                        $(acceptType.split(',')).each(function(i, type) {
                            type = type.trim();
                            if ((type.substring(type.length - 1) == '*' && mime.indexOf(type.substring(0, type.length - 1)) == 0) || type == mime) {
                                accept = true;
                                return false;
                            }
                        });
                    }
                    return accept;
                }
            });

            // 上传成功
            scope.uploader.onSuccessItem = function(fileItem, response, status, headers) {
                $(elem).find("input").val("");
                var file = response.data;
                file.author = scope.author.name;

                if (scope.multiple) {// 多选
                    var files = ngModelController.$viewValue || [];
                    files.push(file);
                    // call $parsers pipeline then update $modelValue
                    ngModelController.$setViewValue(files);
                } else {// 单选
                    ngModelController.$setViewValue(file);
                }
                // update the local view
                ngModelController.$render();
            };

            scope.uploader.onCompleteAll = function() {
                scope.uploader.clearQueue();
            };

            // 删除文件
            scope.delete = function(file) {
                if (scope.multiple) {// 多选
                    var files = [];
                    for (var i = 0, len = ngModelController.$viewValue.length; i < len; i++) {
                        var f = ngModelController.$viewValue[i];
                        if (file.url != f.url) {
                            files.push(f);
                        }
                    }
                    // call $parsers pipeline then update $modelValue
                    ngModelController.$setViewValue(files);
                } else {
                    ngModelController.$setViewValue(null);
                }
                // update the local view
                ngModelController.$render();
            }
        }

    };
}]);
